{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 简易聊天机器人\n",
    "### 目标：\n",
    "#### 代码结构分层：UI层（view)，(admin/control)数据管理层\n",
    "#### 数据读写pkl:pickle，当作简易的数据库存储信息\n",
    "#### 聊天机器人简介:积累大量语料，然后根据输入语句，进行分词，语义分析后，去语料库寻找相关的输入与输出语句，结合实际输入内容，返回最接近的答案。\n",
    "#### 分析:\n",
    "#### 机器人需要能听，能说，这部分是最外层，直接与人接触，我们叫层，或者表现层，展示层。\n",
    "#### 还需要一部分实际处理数据，对听的内容进行分析，然后返回答案让机器人说出来，这就是管理层或者数据层了。\n",
    "#### UI层调用数据层的功能(接口)完成对外的多种交互。分工合作，和谐社会。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "import time\n",
    "\n",
    "\n",
    "# 准备语料库\n",
    "data = {'早上好':'早',\n",
    "        '天气怎么样':'多云转晴，温度26度，北转南风七八级',\n",
    "        'python怎么学':'请找De8uG'\n",
    "       }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读写语料库\n",
    "def rw_data(str_from):\n",
    "        if str_from in data:\n",
    "            print(f'De8ug:{data[str_from]}')\n",
    "        elif str_from == '':\n",
    "                print(\"De8ug：是和我无话可说嘛？\")\n",
    "                str_from  = input('De8ug：那您可以按q退出')\n",
    "                if str_from == 'q':\n",
    "                    print('欢迎以后常来聊')\n",
    "                    return False\n",
    "                    \n",
    "                \n",
    "        elif str_from not in data:\n",
    "            data[str_from] = input(f'“{str_from}”没有对应的语料库，请帮我完善：')\n",
    "            print(data[str_from])\n",
    "            print('谢谢!我变得更会与人聊天了!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def main():\n",
    "    # 读取语料库\n",
    "    with open('yl.pkl', 'rb') as f:\n",
    "        data = pickle.loads(f.read())\n",
    "        print(data)\n",
    "    user = input(\"请输入用户名:\" )\n",
    "    print(f'我是De8ug机器人，很高兴能和您聊天')\n",
    "    while True: \n",
    "        str_from = input(f'{user}：')\n",
    "        rw_data(str_from)\n",
    "        False\n",
    "        with open('yl.pkl', 'wb') as f:\n",
    "            f.write(pickle.dumps(data))\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
